package htmodels

import (
	"github.com/astaxie/beego/orm"
	"anfang/models"
	"time"
	"log"
)

func HTDevicesAdd(devices *models.Devices) error {
	o := orm.NewOrm()
	_, err := o.Insert(devices)
	return err
}

func HTDevicesGetDetail(devices *models.Devices) error {
	o := orm.NewOrm()
	return o.Read(devices)
}

func HTDevicesGetCount(search string, searchFiled string, DeviceType int) (int64, error) {
	o := orm.NewOrm()
	m := models.Devices{}
	count, err := o.QueryTable(m.TableName()).Filter(m.FN_DeviceType(), DeviceType).Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTDevicesGetList(devicess *[]models.Devices, fields []string, DeviceType int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.Devices{}
	qs := o.QueryTable(m.TableName())
	if DeviceType != 0 {
		qs = qs.Filter(m.FN_DeviceType(), DeviceType)
	}
	_, err := qs.Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(devicess, fields...)
	return err
}

func HTDevicesDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.Devices{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}
func HTDevicesUpdate(devices *models.Devices) error {
	o := orm.NewOrm()
	_, err := o.Update(devices)
	return err
}

func GetDeviceByDeviceNameAndDevicePass(devicesName string, devicePass string) (DeviceId int, DeviceType int, err error) {
	o := orm.NewOrm()
	m := models.Devices{}
	err = o.QueryTable(m.TableName()).Filter(m.FN_DeviceAuthName(), devicesName).Filter(m.FN_DeviceAuthPass(), devicePass).One(&m)
	DeviceId = m.Id
	DeviceType = m.DeviceType
	return
}

func UpdataDeviceTime(Id int) {
	o := orm.NewOrm()
	m := models.Devices{Id:Id}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_Id(), Id).Update(orm.Params{
		m.FN_DeviceUpdateTime(): time.Now()})
	if err != nil {
		log.Printf("update time error when update Device:%d\r\n", Id)
	}
}

func GetDevicesOffLine(devicess *[]models.Devices, timeDuration time.Duration) error {
	o := orm.NewOrm()
	m := models.Devices{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_DeviceStatus(), 1).Filter(m.FN_DeviceUpdateTime() + "__lt", time.Now().Add(-timeDuration)).All(devicess)
	return err
}
